package org.dromara.web.plugins.telegram;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.base.Enums;
import com.pengrad.telegrambot.TelegramBot;
import com.pengrad.telegrambot.UpdatesListener;
import com.pengrad.telegrambot.model.BotCommand;
import com.pengrad.telegrambot.model.MessageEntity;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.request.*;
import com.pengrad.telegrambot.request.SendMessage;
import com.pengrad.telegrambot.request.SendPhoto;
import com.pengrad.telegrambot.request.SetMyCommands;
import com.pengrad.telegrambot.response.BaseResponse;
import com.pengrad.telegrambot.response.SendResponse;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.dao.business.domain.*;
import org.dromara.dao.business.enums.UserTypeEnums;
import org.dromara.dao.business.mapper.ModelMapper;
import org.dromara.dao.business.mapper.SmartAgentMapper;
import org.dromara.dao.business.mapper.UserTypeSettingMapper;
import org.dromara.web.plugins.provider.ModelProviderFactory;
import org.dromara.web.service.business.SettingsService;
import org.dromara.web.service.business.SmartAgentCategoryService;
import org.dromara.web.service.business.SmartAgentService;
import org.dromara.web.service.business.UserService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;



@Slf4j
//@Component
public class TelegramBotPluginsV2 implements InitializingBean {


    TelegramBot bot;

    private static final String TELETRAM_BOT_URL = "https://t.me/JingJingLingBot";
    private static final String TELEGRAM_BOT_TOKEN = "8083414280:AAGB6jAb7W1oQ64-7z-v88JD6wVfHcNAJLo";

    private static final String WELCOME_MESSAGE = "欢迎使用MieraChatBot, 请在菜单栏中选择需要的操作";
    private static final String WELCOME_MESSAGE_MAIN = "\uD83C\uDF10<strong>欢迎体验Miera</strong>\uD83C\uDF10想让AI为您解锁超能力吗?Miera是您的超酷的伙伴, 融合全球顶尖大语言模型,强大又有趣,随时为您服务\uD83D\uDE80\n" +
        " \uD83D\uDD04<b>自由切换模型</b>: 随心切换大模型,效率飙升so easy\n" +
        " \uD83D\uDCAA<b>多样化智能体</b>: 专业助力，乐趣无穷覆盖:\n" +
        "     <b>编程</b>: 代码小白秒变大神编程so simple\n" +
        "     <b>创作</b>: 灵感枯竭?AI助您妙笔生花。\n" +
        "     <b>情感</b>: 孤独时有我，暖心陪伴不打烊\n" +
        "     <b>决策</b>: 纠结bye bye,AI帮您果断出手\n" +
        "     更多惊喜领域,等您挖掘\n" +
        " <b>个性化助手</b>: 打造您的专属AI小精灵,独一无二,超有范儿\n" +
        " <b>Miera</b>已经就位！限时免费试用m，马上抢位，AI之旅即刻开启⏳\uFE0F\uD83C\uDF81<b>随时随地体验，PC,网页，APP多端版本任您选择，下载即刻开启</b>";
    private static final String ERROR_MESSAGE = "系统异常，请联系管理员";



    private static final String COMMAND_MODEL_SELECT = "✨\uFE0F选择对话模型";
    private static final String COMMAND_ASSISTANT = "\uD83D\uDC6D智能助手";
    private static final String COMMAND_UPGRADE_AI = "\uD83D\uDCB9升级Miera AI";
    private static final String COMMAND_PERSONAL = "\uD83D\uDE46个人中心";
    private static final String COMMAND_CONTACT_CUSTOMER = "\uD83D\uDCDE联系客服";
    private static final String COMMAND_INVITE = "\uD83E\uDD3C\u200D♂\uFE0F邀请好友";


    private static final String URL_WELCOME_IMAGE = "https://img1.baidu.com/it/u=406627714,1734238609&fm=253&fmt=auto&app=120&f=JPEG?w=1324&h=800";

    private static final String URL_EXPERIENCE = "https://api.telegram.org";
    private static final String URL_H5 = "https://api.telegram.org";
    private static final String URL_DOWNLOAD_APP = "https://api.telegram.org";
    private static final String URL_PC = "https://api.telegram.org";
    private static final String URL_CUSTOMER = "https://api.telegram.org";


    private static final String USER_NAME_FORMAT = "telegram-u-%s";

    @Autowired
    ThreadPoolTaskExecutor  threadPoolTaskExecutor;
    @Autowired
    UserService userService;
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    ModelProviderFactory modelProviderFactory;
    @Autowired
    SmartAgentMapper smartAgentMapper;
    @Autowired
    SettingsService settingsService;
    @Autowired
    UserTypeSettingMapper userTypeSettingMapper;
    @Autowired
    SmartAgentCategoryService smartAgentCategoryService;
    @Autowired
    SmartAgentService smartAgentService;

    @Override
    public void afterPropertiesSet() throws Exception {
        bot = new TelegramBot(TELEGRAM_BOT_TOKEN);


        bot.setUpdatesListener(updates -> {
            // ... process updates
            threadPoolTaskExecutor.execute(() -> {
                updates.stream().forEach(update -> {
                    dealUpdate(update);
                });
            });
            // return id of last processed update or confirm them all
            return UpdatesListener.CONFIRMED_UPDATES_ALL;
// Create Exception Handler
        }, e -> {
            if (e.response() != null) {
                // got bad response from telegram
                e.response().errorCode();
                e.response().description();
            } else {
                // probably network error
                e.printStackTrace();
            }
        });
    }



    private void dealUpdate(final Update update) {
        log.info("update:{}", JSON.toJSONString(update));
        Long chatId = update.message().chat().id();
        Integer messageId = update.message().messageId();
        String text = update.message().text();
        Long fromUserId = update.message().from().id();
        // 检查是否注册
        threadPoolTaskExecutor.execute(()->{
            userService.telegramUserRegister(username(update.message().from().id()));
        });

        try {
            if (StringUtils.isNotEmpty(text)) {
                if (COMMAND_PERSONAL.equals(text)) {
                    showPersonalCenter(chatId, fromUserId, update.message().from().username(), messageId);
                    return;
                } else if (COMMAND_INVITE.equals(text)) {
                    showInvite(chatId, messageId);
                    return;
                } else if (COMMAND_ASSISTANT.equals(text)) {
                    showAgentCategory(chatId);
                    return;
                } else if (COMMAND_CONTACT_CUSTOMER.equals(text)) {
                    showCustomer(chatId);
                    return;
                } else if (COMMAND_MODEL_SELECT.equals(text)) {
                    showModelSelectList(chatId);
                    return;
                } else if (COMMAND_UPGRADE_AI.equals(text)) {
                    showUpgrade(chatId);
                    return;
                } else if ("/start myAgent".equals(text)) {
                    showMyAgentList(chatId, fromUserId);
                    return;
                } else if ("/start myAccount".equals(text)) {
                    showPersonalCenter(chatId, fromUserId, update.message().from().username(), messageId);
                    return;
                } else if ("/start myHistory".equals(text)) {

                } else if ("/start gradeList".equals(text)) {
                    showGradeList(chatId);
                    return;
                } else if (text.startsWith("/start GRADE")) {
                    String gradeType = text.replace("/start ", "");
                    TelegramGradePackage grade = TelegramGradePackage.valueOf(gradeType);
                    showGradeRecharge(chatId, fromUserId);
                    return;
                } else if (text.startsWith("/start model")) {
                    Long modelId = Long.parseLong(text.replace("/start model", ""));
                    cacheUserModel(username(fromUserId), modelId);
                    SendMessage sendMessage = new SendMessage(chatId, "选择模型成功，立即开始对话");
                    bot.execute(sendMessage);
                    return;
                } else if (text.startsWith("/start upgrade")) {
                    String type = text.replace("/start upgrade", "");
                    showUpgradeResponse(chatId, fromUserId, type);
                    return;
                } else if (text.startsWith("/start CA")) {
                    String categoryId = text.replace("/start CA", "");
                    showAgentList(chatId, Long.parseLong(categoryId));
                    return;
                } else if (text.startsWith("/start")) {
                    showMainReplyKeyboard(chatId, WELCOME_MESSAGE);
                    showWelcomeKeyboard(chatId);
                    return;
                }

                Long modelId = getUserModel(username(fromUserId));
                if (modelId == null) {
                    showModelSelectList(chatId);
                    return;
                }
                Model model = modelMapper.selectById(modelId);
                if (model == null) {
                    showModelSelectList(chatId);
                    return;
                }

                try{
                    User user = userService.telegramUserInfo(username(fromUserId));
                    if (UserTypeEnums.USER_TYPE_COMMON.equals(user.getUserType())) {
                        userService.userBalanceChange(user.getId(), - model.getDiamondFee(), - model.getStarFee(), "模型调用");
                    } else {
                        if (user.getUserTypeEnd() == null || user.getUserTypeEnd().isBefore(LocalDateTime.now())) {
                            showUpgrade(chatId);
                            return;
                        }
                    }

                }catch (Exception e) {
                    showUpgrade(chatId);
                    return;
                }

                String aiResponse = modelProviderFactory.chatResponse(model, text);
                String response = model.getName() + ": " + aiResponse;

                SendMessage sendMessage = new SendMessage(chatId, response);
                SendResponse sendResponse = bot.execute(sendMessage);

                return;

            }


        }catch (Exception e) {
            e.printStackTrace();
//            showWelcomeKeyboard(chatId);
//            return;
        }

        showMainReplyKeyboard(chatId, WELCOME_MESSAGE);
        showWelcomeKeyboard(chatId);
    }





    private void showModelSelectList(Long chatId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        List<Model> models = modelMapper.selectList(new LambdaQueryWrapper<Model>().eq(Model::getStatus, true));
        if (CollectionUtils.isNotEmpty(models)) {
            int rows = (models.size() + 1) / 2;
            for (int i = 0; i < rows; i++) {
                if ( i == rows - 1 && models.size() % 2 == 1) {
                    Model model= models.get(2 * i);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(models.get(2 * i).getName() + "-" + (model.getStarFee() != null && model.getStarFee() > 0 ? (model.getStarFee() + "高级积分") : (model.getDiamondFee() + "基础积分")),
                        TELETRAM_BOT_URL + "?start=model" + model.getId()));
                } else {
                    Model model1 = models.get(2 * i);
                    Model model2 = models.get(2 * i + 1);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(model1.getName() + "-" + (model1.getStarFee() != null && model1.getStarFee() > 0 ? (model1.getStarFee() + "高级积分") : (model1.getDiamondFee() + "基础积分")),
                            TELETRAM_BOT_URL + "?start=model" + model1.getId()),
                        new InlineKeyboardButton(model2.getName() + "-" + (model2.getStarFee() != null && model2.getStarFee() > 0 ? (model2.getStarFee() + "高级积分") : (model2.getDiamondFee() + "基础积分")),
                            TELETRAM_BOT_URL + "?start=model" + model2.getId()));
                }
            }
        }
        Map<String,String> settings =  settingsService.getSettingsMap();
        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .caption("每日赠送" + settings.get("common_reset_star_count") + "高级积分" + settings.get("common_reset_diamond_count") + "基础积分, 每日0点重置\n\n选择模型即可开启对话")
            .parseMode(ParseMode.HTML)
            .replyMarkup(inlineKeyboardMarkup);
        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }


    private void showMyAgentList(Long chatId, Long fromUserId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();

        User user = userService.telegramUserInfo(username(fromUserId));
        List<SmartAgent> smartAgents = smartAgentMapper.selectList(new LambdaQueryWrapper<SmartAgent>().eq(SmartAgent::getUserId, user.getId()));
        if (CollectionUtils.isNotEmpty(smartAgents)) {
            int rows = (smartAgents.size() + 1) / 2;
            for (int i = 0; i < rows; i++) {
                if ( i == rows - 1 && smartAgents.size()  % 2 == 1) {
                    SmartAgent smartAgent = smartAgents.get(2 * i);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(smartAgents.get(2 * i).getName(), TELETRAM_BOT_URL + "?start=agent" + smartAgent.getId()));
                } else {
                    SmartAgent agent1 = smartAgents.get(2 * i);
                    SmartAgent agent2 = smartAgents.get(2 * i + 1);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(agent1.getName(), TELETRAM_BOT_URL + "?start=agent" + agent1.getId()),
                        new InlineKeyboardButton(agent2.getName(), TELETRAM_BOT_URL + "?start=agent" + agent2.getId()));
                }
            }
        }

        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .replyMarkup(inlineKeyboardMarkup);
        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }


    private void showPersonalCenter(Long chatId,Long fromUserId,String fromUsername, Integer messageId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("我的智能体", TELETRAM_BOT_URL+ "?start=myAgent"),
            new InlineKeyboardButton("我的账户",TELETRAM_BOT_URL+ "?start=myAccount"));
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("历史对话",URL_H5));
        User user = userService.telegramUserInfo(username(fromUserId));
        String message = new StringBuffer()
            .append("用户ID: ").append(user.getId()).append("\n")
            .append("电报ID: ").append(fromUserId).append("\n")
            .append("电报昵称: ").append(fromUsername).append("\n")
            .append("基础积分: ").append(user.getBalanceDiamond()).append("\n")
            .append("高级积分: ").append(user.getBalanceStar()).append("\n")
            .append("订阅到期日期: ").append(user.getUserTypeEnd() == null ? "" : DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD).format(user.getUserTypeEnd())).append("\n")
            .toString();

        SendMessage sendMessage = new SendMessage(chatId, message)
            .parseMode(ParseMode.HTML)
            .replyParameters(new ReplyParameters(messageId))
            .replyMarkup(inlineKeyboardMarkup);
        SendResponse response1 = bot.execute(sendMessage);
        log.debug(JSON.toJSONString(response1));
    }


    private void  showUpgrade(Long chatId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("订购基础版-1个月", TELETRAM_BOT_URL + "?start=upgrade1"),
            new InlineKeyboardButton("订购基础版-12个月",TELETRAM_BOT_URL + "?start=upgrade2"));
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("订购高级版-1个月", TELETRAM_BOT_URL + "?start=upgrade3"),
            new InlineKeyboardButton("订购高级版-12个月",TELETRAM_BOT_URL + "?start=upgrade4"));
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("订购加油包", TELETRAM_BOT_URL + "?start=gradeList"),
            new InlineKeyboardButton("个人中心", TELETRAM_BOT_URL + "?start=myAccount"));
        UserTypeSetting type1Setting1 = userTypeSettingMapper.selectOne(new LambdaQueryWrapper<UserTypeSetting>().eq(UserTypeSetting::getUserType, UserTypeEnums.USER_TYPE_MOBILE));
        UserTypeSetting type1Setting2 = userTypeSettingMapper.selectOne(new LambdaQueryWrapper<UserTypeSetting>().eq(UserTypeSetting::getUserType, UserTypeEnums.USER_TYPE_ALL));
        String content = "基础版\n" +
            "\n" +
            "畅享 GPT-4O MINI 等轻量模型\n" +
            "\n" +
            (type1Setting1 == null ? "0.00" : type1Setting1.getMonthFee()) + "/月  " + (type1Setting1 == null ? "0.00" : type1Setting1.getYearFee()) + "/年 USDT\n" +
            "无积分限制。移动端, Telegram端可用, 全平台工具智能体随时可用.\n" +
            "\n" +
            "高级版\n" +
            "\n" +
            "解锁 GPT-4O CLAUDE 3.5 SONNET等强大模型，支持上下文和复杂推理。 立即升级体验更多\n" +
            "\n" +
            (type1Setting2 == null ? "0.00" : type1Setting2.getMonthFee()) + "/月  " + (type1Setting2 == null ? "0.00" : type1Setting2.getYearFee()) + "/年 USDT\n" +
            "无积分限制。PC、网页、移动端、Telegram端可用, 全平台工具智能体随时可用。";
        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .caption(content)
            .parseMode(ParseMode.HTML)
            .replyMarkup(inlineKeyboardMarkup);

        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }


    private void  showGradeList(Long chatId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        TelegramGradePackage[] packages = TelegramGradePackage.values();
        StringBuilder content = new StringBuilder("加油包详情:\n积分不会过期套餐内所有积分适用于所有高级模型。\n");
        int rows = (packages.length + 1) / 2;
        for (int i = 0; i < rows; i++) {
            if ( i == rows - 1 && packages.length  % 2 == 1) {
                TelegramGradePackage grade = packages[2 * i];
                inlineKeyboardMarkup.addRow(new InlineKeyboardButton(grade.getGrade() + "高级积分", TELETRAM_BOT_URL + "?start=" + grade.name()));
                content.append(grade.getGrade()).append("高级积分 ").append(grade.getAmount()).append("USDT \n");
            } else {
                TelegramGradePackage grade1 = packages[2 * i];
                content.append(grade1.getGrade()).append("高级积分 ").append(grade1.getAmount()).append("USDT ");
                TelegramGradePackage grade2 = packages[2 * i + 1];
                content.append(grade2.getGrade()).append("高级积分 ").append(grade2.getAmount()).append("USDT \n");
                inlineKeyboardMarkup.addRow(new InlineKeyboardButton(grade1.getGrade() + "高级积分", TELETRAM_BOT_URL + "?start=" + grade1.name()),
                    new InlineKeyboardButton(grade2.getGrade() + "高级积分", TELETRAM_BOT_URL + "?start=" + grade2.name()));
            }
        }

        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .caption(content.toString())
            .parseMode(ParseMode.HTML)
            .replyMarkup(inlineKeyboardMarkup);

        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }


    private void  showGradeRecharge(Long chatId, Long fromUserId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("联系客服", URL_CUSTOMER));
        TelegramGradePackage[] packages = TelegramGradePackage.values();
        String address = userService.telegramUserHighAddress(username(fromUserId));
        StringBuilder content = new StringBuilder("充值钱包地址(ERC20): \n" + address + "\n" +
            "-----------------------------------------------------\n");
        int rows = (packages.length + 1) / 2;
        for (int i = 0; i < rows; i++) {
            if ( i == rows - 1 && packages.length  % 2 == 1) {
                TelegramGradePackage grade = packages[2 * i];

                content.append(grade.getGrade()).append("高级积分 ").append(grade.getAmount()).append("USDT \n");
            } else {
                TelegramGradePackage grade1 = packages[2 * i];
                content.append(grade1.getGrade()).append("高级积分 ").append(grade1.getAmount()).append("USDT ");
                TelegramGradePackage grade2 = packages[2 * i + 1];
                content.append(grade2.getGrade()).append("高级积分 ").append(grade2.getAmount()).append("USDT \n");

            }
        }
        content.append("-----------------------------------------------------\n\uD83D\uDCAC温馨提示:\n" +
            "  1\uFE0F⃣ 充值成功后，积分可能会在1-5分钟内到账\n  2\uFE0F⃣ 请仔细确认充值地址是否有误");

        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .caption(content.toString())
            .parseMode(ParseMode.HTML)
            .replyMarkup(inlineKeyboardMarkup);

        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }


    /**
     * 用户选择的种类
     *  1 移动端1个月
     *  2 移动端12个月
     *  3 全端1个月
     *  4 全端12个月
     *  5 充值基础积分
     *  6 充值高级积分
     *
     * @param chatId
     * @param fromUserId
     * @param type
     */
    private void  showUpgradeResponse(Long chatId, Long fromUserId, String type) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("联系客服", URL_CUSTOMER));
        String content = "";
        String address = userService.telegramUserLowAddress(username(fromUserId));
        if ("1".equals(type) || "2".equals(type)) {
            // 移动端
            UserTypeSetting type1Setting1 = userTypeSettingMapper.selectOne(new LambdaQueryWrapper<UserTypeSetting>().eq(UserTypeSetting::getUserType, UserTypeEnums.USER_TYPE_MOBILE));
            if ("1".equals(type)) {
                content = "充值钱包地址(ERC20): \n" + address + "\n" +
                    "-----------------------------------------------------\n" +
                    "基础版\n" +
                    "\n" +
                    "畅享 GPT-4O MINI 等轻量模型\n" +
                    "\n" +
                    (type1Setting1 == null ? "0.00" : type1Setting1.getMonthFee()) + "/月 USDT\n" +
                    "无积分限制。移动端, Telegram端可用, 全平台工具智能体随时可用.\n" +
                    "-----------------------------------------------------\n\uD83D\uDCAC温馨提示:\n" +
                    "  1\uFE0F⃣ 充值成功后，积分可能会在1-5分钟内到账\n  2\uFE0F⃣ 请仔细确认充值地址是否有误";
            } else {
                content = "充值钱包地址(ERC20): \n" + address + "\n" +
                    "-----------------------------------------------------\n" +
                    "基础版\n" +
                    "\n" +
                    "畅享 GPT-4O MINI 等轻量模型\n" +
                    "\n" +
                    (type1Setting1 == null ? "0.00" : type1Setting1.getYearFee()) + "/年 USDT\n" +
                    "无积分限制。移动端, Telegram端可用, 全平台工具智能体随时可用.\n" +
                    "-----------------------------------------------------\n\uD83D\uDCAC温馨提示:\n" +
                    "  1\uFE0F⃣ 充值成功后，积分可能会在1-5分钟内到账\n  2\uFE0F⃣ 请仔细确认充值地址是否有误";
            }
        } else if ("3".equals(type) || "4".equals(type)) {
            // 全端版
            UserTypeSetting type1Setting2 = userTypeSettingMapper.selectOne(new LambdaQueryWrapper<UserTypeSetting>().eq(UserTypeSetting::getUserType, UserTypeEnums.USER_TYPE_ALL));
            if ("3".equals(type)) {
                content = "充值钱包地址(ERC20): \n" + address + "\n" +
                    "-----------------------------------------------------\n" +
                    "高级版\n" +
                    "\n" +
                    "解锁 GPT-4O CLAUDE 3.5 SONNET等强大模型，支持上下文和复杂推理。 立即升级体验更多\n" +
                    "\n" +
                    (type1Setting2 == null ? "0.00" : type1Setting2.getMonthFee()) + "/月 USDT\n" +
                    "无积分限制。PC、网页、移动端、Telegram端可用, 全平台工具智能体随时可用。\n" +
                    "-----------------------------------------------------\n\uD83D\uDCAC温馨提示:\n" +
                    "  1\uFE0F⃣ 充值成功后，积分可能会在1-5分钟内到账\n  2\uFE0F⃣ 请仔细确认充值地址是否有误";
            } else {
                content = "充值钱包地址(ERC20): \n" + address + "\n" +
                    "-----------------------------------------------------\n" +
                    "高级版\n" +
                    "\n" +
                    "解锁 GPT-4O CLAUDE 3.5 SONNET等强大模型，支持上下文和复杂推理。 立即升级体验更多\n" +
                    "\n" +
                    (type1Setting2 == null ? "0.00" : type1Setting2.getYearFee()) + "/年 USDT\n" +
                    "无积分限制。PC、网页、移动端、Telegram端可用, 全平台工具智能体随时可用。\n" +
                    "-----------------------------------------------------\n\uD83D\uDCAC温馨提示:\n" +
                    "  1\uFE0F⃣ 充值成功后，积分可能会在1-5分钟内到账\n  2\uFE0F⃣ 请仔细确认充值地址是否有误";
            }
        } else {
            content = "充值钱包地址(ERC20): \n" + address + "\n" +
                "-----------------------------------------------------\n" +
                "请往以上地址充值您需要的积分数额 1USDT=1" + ("5".equals(type) ? "基础积分" : "高级积分") + "\n" +
                "-----------------------------------------------------\n\uD83D\uDCAC温馨提示:\n" +
                "  1\uFE0F⃣ 充值成功后，积分可能会在1-5分钟内到账\n  2\uFE0F⃣ 请仔细确认充值地址是否有误";
        }



        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .caption(content)
            .parseMode(ParseMode.HTML)
            .replyMarkup(inlineKeyboardMarkup);

        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }



    private void  showAgentCategory(Long chatId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        List<SmartAgentCategory> categories = smartAgentCategoryService.getValidCategory("zh_CN");
        if (CollectionUtils.isNotEmpty(categories)) {
            int rows = (categories.size() + 1) / 2;
            for (int i = 0; i < rows; i++) {
                if ( i == rows - 1 && categories.size() % 2 == 1) {
                    SmartAgentCategory grade = categories.get(2 * i);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(grade.getName(), TELETRAM_BOT_URL + "?start=CA" + grade.getId()));
                } else {
                    SmartAgentCategory grade1 = categories.get(2 * i);
                    SmartAgentCategory grade2 = categories.get(2 * i + 1);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(grade1.getName(), TELETRAM_BOT_URL + "?start=CA" + grade1.getId()),
                        new InlineKeyboardButton(grade2.getName(), TELETRAM_BOT_URL + "?start=CA" + grade2.getId()));

                }
            }
        }
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("创建智能体", URL_H5),
            new InlineKeyboardButton("我的智能体", TELETRAM_BOT_URL+ "?start=myAgent"));
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("文生图(跳转网页)", URL_H5), new InlineKeyboardButton("历史会话", URL_H5));
        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .replyMarkup(inlineKeyboardMarkup);
        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }

    private void  showAgentList(Long chatId, Long categoryId) {

        List<SmartAgent> smartAgents = smartAgentService.getSmartAgent(categoryId, "", "zh_CN", null);
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        if (CollectionUtils.isNotEmpty(smartAgents)) {
            int rows = (smartAgents.size() + 1) / 2;
            for (int i = 0; i < rows; i++) {
                if ( i == rows - 1 && smartAgents.size() % 2 == 1) {
                    SmartAgent smartAgent = smartAgents.get(2 * i);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(smartAgents.get(2 * i).getName(), TELETRAM_BOT_URL + "?start=agent" + smartAgent.getId()));
                } else {
                    SmartAgent agent1 = smartAgents.get(2 * i);
                    SmartAgent agent2 = smartAgents.get(2 * i + 1);
                    inlineKeyboardMarkup.addRow(new InlineKeyboardButton(agent1.getName(), TELETRAM_BOT_URL + "?start=agent" + agent1.getId()),
                        new InlineKeyboardButton(agent2.getName(), TELETRAM_BOT_URL + "?start=agent" + agent2.getId()));
                }
            }
        }

        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("前端首页", URL_H5),
            new InlineKeyboardButton("历史会话", URL_H5));
        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .replyMarkup(inlineKeyboardMarkup);

        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }



    private void showCustomer(Long chatId) {
        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("点击联系客服", URL_CUSTOMER));
        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .replyMarkup(inlineKeyboardMarkup);

        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }


    private void showInvite(Long chatId, Integer messageId) {
        Map<String,String> settings =  settingsService.getSettingsMap();
        SendMessage sendMessage = new SendMessage(chatId, "推广链接1 (飞机邀请): " + "https://t.me/xxxx" + "\n"
            + "推广链接2 (飞机邀请): " + "https://t.me/xxxx" + "\n\n"
            + "成功邀请1位好友可获得: " + settings.get("invite_diamond_count") + "基础积分 " + settings.get("invite_star_count")+ "高级积分")
            .replyParameters(new ReplyParameters(messageId));
        SendResponse response = bot.execute(sendMessage);
        log.debug(JSON.toJSONString(response));
    }

    private void showMainReplyKeyboard(Long chatId, String text) {
        Keyboard replyKeyboardMarkup = new ReplyKeyboardMarkup(
            new String[]{COMMAND_MODEL_SELECT, COMMAND_ASSISTANT},
            new String[]{COMMAND_UPGRADE_AI, COMMAND_PERSONAL},
            new String[]{COMMAND_CONTACT_CUSTOMER, COMMAND_INVITE})
            .oneTimeKeyboard(false)   // optional
            .resizeKeyboard(true)    // optional
            .selective(false);        // optional
        SendMessage sendMessage = new SendMessage(chatId, text)
            .replyMarkup(replyKeyboardMarkup);
        SendResponse response = bot.execute(sendMessage);
        log.debug(JSON.toJSONString(response));
    }

    private void showWelcomeKeyboard(Long chatId) {

        InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup();
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("立即体验", URL_EXPERIENCE),
            new InlineKeyboardButton("使用网页版(功能更全)",URL_H5));
        inlineKeyboardMarkup.addRow(new InlineKeyboardButton("下载APP(图片生成)",URL_DOWNLOAD_APP),
            new InlineKeyboardButton("下载PC版(办公助手)",URL_PC));
        SendPhoto sendPhoto = new SendPhoto(chatId, URL_WELCOME_IMAGE)
            .caption(WELCOME_MESSAGE_MAIN)
            .parseMode(ParseMode.HTML)
            .replyMarkup(inlineKeyboardMarkup);

        SendResponse response1 = bot.execute(sendPhoto);
        log.debug(JSON.toJSONString(response1));
    }

    private String username(Long userId) {
        return String.format(USER_NAME_FORMAT, userId.toString());
    }


    private void cacheUserModel(String username, Long modelId) {
        redisTemplate.opsForValue().set("TELEGRAM_USER_MODEL_SELECTION:" + username, modelId + "");

    }

    private Long getUserModel(String username) {
        String ret = redisTemplate.opsForValue().get("TELEGRAM_USER_MODEL_SELECTION:" + username);
        return StringUtils.isEmpty(ret) ? null : Long.parseLong(ret);
    }


    public static enum TelegramGradePackage {

        GRADE_1(new BigDecimal(15), 200),
        GRADE_2(new BigDecimal(30), 400),
        GRADE_3(new BigDecimal(45), 400),
        GRADE_4(new BigDecimal(60), 400),
        GRADE_5(new BigDecimal(75), 400),
        GRADE_6(new BigDecimal(90), 400),
        GRADE_7(new BigDecimal(105), 400),
        GRADE_8(new BigDecimal(120), 400),
        GRADE_9(new BigDecimal(135), 400),
        GRADE_10(new BigDecimal(150), 400),
        ;

        private BigDecimal amount;
        private Integer grade;

        private TelegramGradePackage(BigDecimal amount, Integer grade) {
            this.amount = amount;
            this.grade = grade;
        }


        public BigDecimal getAmount() {
            return amount;
        }

        public Integer getGrade() {
            return grade;
        }
    }
}
